package com.supor.aiot.ui.privacy;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;

import com.alipay.mobile.framework.quinoxless.QuinoxlessFramework;
import com.android.baseconfig.base.AndroidWorkaround;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.GetAndroidUniqueMark;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.constact.AppGlobalHost;
import com.supor.aiot.R;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.AppInit;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.push.PushMsgService;
import com.supor.aiot.common.ui.activity.WebActivity;
import com.supor.aiot.databinding.ActivityAuthPrivacyBinding;
import com.supor.aiot.mine.ui.activity.DebugSettingActivity;
import com.supor.aiot.util.AuthPrivacyPop;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 权限申请页面 <br>
 * 作者: lei <br>
 * 日期: 2021/1/25 <br>
 */
public class AuthPrivacyActivity extends BaseMVVMActivity<NoViewModel, ActivityAuthPrivacyBinding> implements AuthPrivacyPop.AuthPrivacyCallback {

    boolean[] privacys = {false, false, false, false};
    private RxPermissions rxPermissions;

    @Override
    protected int resourceId() {
        return R.layout.activity_auth_privacy;
    }

    @Override
    protected void initData() {
        super.initData();
        rxPermissions = new RxPermissions(this);
        AuthPrivacyPop.getInstance().initPop(this);
        AuthPrivacyPop.getInstance().setCallback(this);
        // initCmcc();
        bindingView.btnCancel.setOnClickListener(this::onViewClicked);
        bindingView.btnNextStep.setOnClickListener(this::onViewClicked);
        bindingView.tvPrivacyText.setOnClickListener(this::onViewClicked);
        if (AppAgent.isNavigationBarExist) {
            AndroidWorkaround.assistActivity(this, SystemUtils.getNavigationHeight(this));
        } else {
            AndroidWorkaround.assistActivity(this, 0);
        }
    }

    private void initCmcc() {
        ThreadUtils.execute(() -> {
            while (!QuinoxlessFramework.initSuccess() || !SuporPresenter.initSuccess()) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (QuinoxlessFramework.initSuccess()) {
                runOnUiThread(() -> {
                    Activity activity = ActivityManager.getActivity(0);
                    if (activity != null && SuporPresenter.getInstance().getCmccHelper() == null) {
                        SuporPresenter.getInstance().initCmcc(activity);
                    }
                });
            }
        });
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return true;
    }

    public void initView() {
        bindingView.btnCancel.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        bindingView.btnNextStep.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));

        String tip = getString(R.string.privacy_title_tip1);
        SpannableString spannableString = new SpannableString(tip);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERSERVERAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan1, tip.indexOf("用户服务协议") - 1, tip.indexOf(
                "用户服务协议") + 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERPRIVACYAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan2, tip.indexOf("隐私保护声明") - 1, tip.indexOf("隐私保护声明") + 7,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("用户服务协议") - 1, tip.indexOf("用户服务协议") + 7,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("隐私保护声明") - 1, tip.indexOf("隐私保护声明") + 7,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvPrivacyText1.setText(spannableString);
        bindingView.tvPrivacyText1.setHighlightColor(0x00000000);
        bindingView.tvPrivacyText1.setMovementMethod(LinkMovementMethod.getInstance());
    }

    private void gotoPrivacy(String url) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.Key.param_type, 1);
        bundle.putString(Constants.Key.param_url, url);
        intent.putExtras(bundle);
        intent.setClass(AuthPrivacyActivity.this, WebActivity.class);
        startActivity(intent);
    }

    @SuppressLint({"CheckResult", "AutoDispose"})
    private void checkPermission() {
        BaseSharedPreferences.setInt(SuporApplication.getInstance(),
                Constants.Key.param_authPrivacyPolicy, 1);
        ArrayList<String> permissionArray = new ArrayList<>();
        if (privacys[0]) {
            permissionArray.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            permissionArray.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (privacys[1]) {
            permissionArray.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (privacys[2]) {
            permissionArray.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            permissionArray.add(Manifest.permission.CAMERA);
        }
        // if (privacys[3]) {
        //     permissionArray.add(Manifest.permission.READ_PHONE_STATE);
        // }
        String[] permissionStr = new String[permissionArray.size()];
        permissionArray.toArray(permissionStr);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && permissionArray.size() > 0) {
            rxPermissions.request(permissionStr)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            Logc.i("permission request: success");
                        } else {
                            Logc.i("permission request: failed");
                        }
                        // startTiny();
                        finishPage();
                        // getUniqueId();
                    });
        } else {
            // startTiny();
            finishPage();
            // getUniqueId();
        }
    }

    private void getUniqueId() {
        String uniqueId = BaseSharedPreferences.getString(this, Constants.Key.UNIQUE_ID);
        if (TextUtils.isEmpty(uniqueId)) {
            uniqueId = GetAndroidUniqueMark.getUniqueId(this);
            BaseSharedPreferences.setString(SuporApplication.getInstance(), Constants.Key.UNIQUE_ID, uniqueId);
        }
        Logc.d("getUniqueId: " + uniqueId);
        GlobalDataCache.uniqueId = uniqueId;
        PushMsgService.bindUser();
        PushMsgService.uploadThridToken();
    }

    private void finishPage() {
        // SuporApplication.getInstance().mainHandler.postDelayed(this::finish, 300);
        startActivityForResult(new Intent(this, SplashActivity.class),
                Constants.FIRST_PRIVACY);
        ThreadUtils.execute(() -> {
            // AppInit.getInstance().setup(null);
            AppInit.getInstance().onCreate();
            initCmcc();
            getUniqueId();
        });
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next_step:
                // if (!cbPrivacy.isChecked()) {
                //     ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.privacy_disagree_toast));
                //     return;
                // }
                checkPermission();
                break;
            case R.id.btn_cancel:
                AuthPrivacyPop.getInstance().showPop(this, bindingView.llRoot);
                break;
            case R.id.tv_privacy_text:
                continuousClick();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        setResult(0);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        setResult(resultCode);
        finish();
        overridePendingTransition(0, 0);
        Logc.i("onActivityResult: requestCode: " + requestCode + ", resultCode: " + resultCode);
    }

    @Override
    public void authAgree(boolean agree) {
        if (agree) {
            AuthPrivacyPop.getInstance().dismissPop();
            checkPermission();
        } else {
            // for huawei
            // checkPermission();
            setResult(0);
            finish();
        }
    }

    @Override
    public void onChecked(boolean isChecked) {
        // cbPrivacy.setChecked(isChecked);
    }


    /**
     * 点击次数
     */
    final static int COUNTS = 7;
    /**
     * 规定有效时间
     */
    final static long DURATION = 1500;
    long[] mHits = new long[COUNTS];

    private void continuousClick() {
        //每次点击时，数组向前移动一位
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //为数组最后一位赋值
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
            //重新初始化数组
            mHits = new long[COUNTS];
            //执行逻辑
            // AuthnHelper.setDebugMode(true);
            // AppNetDelegate.setLogger(true);
            // Logc.setLogLevel(Logc.LogLevel.LEVEL_VERBOSE);
            // Logc.i("debug mode is open now!!!");
            // ToastUtils.getInstance().showCustomToast("Debug Mode");
            startActivity(new Intent(this, DebugSettingActivity.class));
            overridePendingTransition(R.anim.activity_open_enter,
                    R.anim.activity_open_exit);
        }
    }
}
